package com.cx.anno;

import java.lang.reflect.Field;

@Logger("user_log")
public class User {
    @NotNull(message = "用户名不能为空")
    private String username;
    @NotNull(message = "昵称不能为空")
    private String nickName;
    public void setUserName(String username){
        this.username = username;
    }
    public void setNickName(String nickName){
        this.nickName = nickName;
    }
    /*@ExceptionHandler(value = "User",message = "校验字段是否为空")
    public void validate() throws Exception {
        // 遍历所有字段
        for (Field field : this.getClass().getDeclaredFields()) {
            // 判断字段上是否有@NotNull注解，如果有抛出注解的message异常
            if (field.isAnnotationPresent(NotNull.class)) {
                field.setAccessible(true);
                // 如果当前对象的字段为空
                  if (field.get(this) == null) {
                      // 获取字段的NotNull注解
                      NotNull notNull = field.getAnnotation(NotNull.class);
                      // 抛出异常，并输出注解中的message信息
                      throw new Exception(notNull.message());
                  }
            }
        }
    }*/
    @ExceptionHandler(value = "User",message = "校验字段是否为空")
    public void test() throws IllegalAccessException {
        Class<? extends User> aClass = this.getClass();
        for (Field field : aClass.getDeclaredFields()) {
            field.setAccessible(true);//设置访问权限
            if(field.isAnnotationPresent(NotNull.class)){
                if(field.get(this)==null){
                    NotNull annotation = field.getAnnotation(NotNull.class);
                    throw new RuntimeException(annotation.message());
                }

            }
        }

    }
}